<template>
  <lay-container fluid="true" class="login-box">
    <lay-card>
      <lay-form style="margin-top: 10px">
        <lay-row>
          <lay-col :md="5">
            <lay-form-item label="用户账号" label-width="80">
              <lay-input
                v-model="searchQuery.userName"
                placeholder="请输入"
                size="sm"
                :allow-clear="true"
                style="width: 98%"
              ></lay-input>
            </lay-form-item>
          </lay-col>
          <lay-col :md="8">
            <lay-form-item label="登录时间" label-width="80">
              <lay-date-picker
                size="sm"
                v-model="searchQuery.rangeTime"
                range
                type="datetime"
                :placeholder="['开始日期', '结束日期']"
              ></lay-date-picker
            ></lay-form-item>
          </lay-col>
          <lay-col :md="5">
            <lay-form-item label-width="20">
              <lay-button
                style="margin-left: 20px"
                type="normal"
                size="sm"
                @click="toSearch"
              >
                查询
              </lay-button>
              <lay-button size="sm" @click="toReset"> 重置 </lay-button>
            </lay-form-item>
          </lay-col>
        </lay-row>
      </lay-form>
    </lay-card>
    <!-- table -->
    <div class="table-box">
      <lay-table
        :page="page"
        :height="'100%'"
        :columns="columns"
        :loading="loading"
        :default-toolbar="true"
        :data-source="dataSource"
        v-model:selected-keys="selectedKeys"
        @change="change"
        @sortChange="sortChange"
      >
        <template #deviceType="{ row }">
          <lay-tooltip :visible="false" trigger="hover" :content="row.deviceType">
            <div class="oneRow">{{ row.deviceType }}</div>
          </lay-tooltip>
        </template>

        <template #status="{ row }">
          <div v-show="row.status == '0'">
            <lay-tag color="#2dc570" variant="light">登录成功</lay-tag>
          </div>
          <div v-show="row.status == '1'">
            <lay-tag color="#F5319D" variant="light">登录失败</lay-tag>
          </div>
        </template>
        <template #msg="{ row }">
          <lay-tooltip :visible="false" trigger="hover" :content="row.msg">
            <div class="oneRow">{{ row.msg }}</div>
          </lay-tooltip>
        </template>
        <template v-slot:toolbar> </template>
        <template v-slot:operator="{ row }">
          <lay-popconfirm
            content="确定要删除此条登录记录吗?"
            @confirm="confirm(row)"
            @cancel="cancel"
          >
            <lay-button size="xs" border="red" border-style="dashed"
              >删除</lay-button
            >
          </lay-popconfirm>
        </template>
      </lay-table>
    </div>
  </lay-container>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { layer } from '@layui/layui-vue'
import { queryLimit, delLoginLog } from '../../../api/module/login-log'

const searchQuery = ref({
  userName: '',
  rangeTime: ['', '']
})

function toReset() {
  searchQuery.value = {
    userName: '',
    rangeTime: ['', '']
  }
  toSearch()
}

async function toSearch() {
  page.current = 1
  await change(page)
}

const loading = ref(false)
const selectedKeys = ref()
const page = reactive({ current: 1, limit: 10, total: 0 })
const columns = ref([
  { title: '用户账号', key: 'userName', sort: 'desc' },
  { title: 'IP地址', key: 'ipaddr', sort: 'desc' },
  {
    title: '设备类型',
    width: '220px',
    key: 'deviceType',
    sort: 'desc',
    customSlot: 'deviceType'
  },
  { title: '操作系统', key: 'os' },
  {
    title: '登录状态',
    width: '120px',
    key: 'status',
    customSlot: 'status'
  },
  { title: '浏览器', key: 'browser' },
  { title: '提示消息', width: '220px', key: 'msg', customSlot: 'msg' },
  { title: '登录时间', width: '220px', key: 'loginTime' },
  { title: '操作', width: '120px', key: 'operator', customSlot: 'operator' }
])
const change = async (pageInfo: any) => {
  loading.value = true
  try {
    const requestBody: any = {
      userName: searchQuery.value.userName
    }
    
    // 添加时间范围查询条件
    if (searchQuery.value.rangeTime[0] && searchQuery.value.rangeTime[1]) {
      requestBody.loginTimeStart = searchQuery.value.rangeTime[0]
      requestBody.loginTimeEnd = searchQuery.value.rangeTime[1]
    }
    
    const queryParams = {
      pageIndex: pageInfo.current,
      pageSize: pageInfo.limit,
      needOrderBy: true, // 自定义排序开启
      orderByMethod: 2, // 2-倒序
      orderByKeyName: 'login_time', // 排序字段
      requestBody: requestBody
    }
    
    const response = await queryLimit(queryParams)
    if (response.code === 200) {
      // 根据后端返回的实际数据结构调整
      const records = response.data.responseBody || []
      dataSource.value = records.map((item: any) => ({
        ...item,
        id: item.id.toString()
      }))
      page.total = response.data.totalNum || 0
      page.current = response.data.pageIndex || 1
      page.limit = response.data.pageSize || 10
    } else {
      layer.msg(response.msg || '查询失败')
    }
  } catch (error) {
    layer.msg('网络请求失败')
    console.error('查询登录日志失败:', error)
  } finally {
    loading.value = false
  }
}
const sortChange = (key: any, sort: number) => {
  layer.msg(`字段${key} - 排序${sort}, 你可以利用 sort-change 实现服务端排序`)
}
const dataSource = ref([])
const changeStatus = (isChecked: boolean, row: any) => {
  dataSource.value.forEach((item: any) => {
    if (item.id === row.id) {
      layer.msg('Success', { icon: 1 }, () => {
        item.ipaddr = isChecked
      })
    }
  })
}
const remove = () => {
  layer.msg(selectedKeys.value, { area: '50%' })
}
async function confirm(row: any) {
  try {
    const response = await delLoginLog([row.id])
    if (response.code === 200) {
      layer.msg('删除成功')
      await toSearch() // 重新加载数据
    } else {
      layer.msg(response.msg || '删除失败')
    }
  } catch (error) {
    layer.msg('删除失败')
    console.error('删除登录日志失败:', error)
  }
}
function cancel() {
  layer.msg('您已取消操作')
}

onMounted(() => {
  toSearch()
})
</script>

<style scoped>
.login-box {
  width: calc(100vw - 220px);
  height: calc(100vh - 110px);
  margin-top: 10px;
  box-sizing: border-box;
  overflow: hidden;
}
.top-search {
  margin-top: 10px;
  padding: 10px;
  height: 40px;
  border-radius: 4px;
  background-color: #fff;
}
.table-box {
  margin-top: 10px;
  padding: 10px;
  height: 700px;
  width: 100%;
  border-radius: 4px;
  box-sizing: border-box;
  background-color: #fff;
}

.search-input {
  display: inline-block;
  width: 98%;
  margin-right: 10px;
}

.isChecked {
  display: inline-block;
  background-color: #e8f1ff;
  color: red;
}
.oneRow {
  width: 220px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>